package com.ship.common.business.mapping;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ship.common.core.exception.SystemException;
import com.ship.common.core.mapping.ContentProvider;
import com.ship.common.core.mapping.Label;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @author 31463
 */
@Component
public class BooleanContentProvider extends ContentProvider {

	public Object getValue(String label, Object currentValue, Object root, Field field, String expression) throws SystemException {
		Label l = field.getAnnotation(Label.class);
		String[] booleanOptions = l.boolOptions();
		if(currentValue == null || "".equals(currentValue)) {
			return null;
		}
		if(currentValue instanceof Boolean) {
			return currentValue;
		}
		
		for(String optionTrue: booleanOptions[0].split("\\|")) {
			if(optionTrue.equals(currentValue)) {
				return true;
			}
		}
		for(String optionFalse: booleanOptions[1].split("\\|")) {
			if(optionFalse.equals(currentValue)) {
				return false;
			}
		}
		throw new SystemException("内容填写错误，请检查有效性 ");
	}

	/**
	 *默认是、否选项，无需重写
	 */
	@Override
	public JSONArray getOptions(Field field) {
		JSONArray options = new JSONArray();
		JSONObject all = createOption("", "未选择");
		all.put("checked", "true");
		JSONObject yes = createOption("true", "是");
		JSONObject no = createOption("false", "否");
		options.add(all);
		options.add(yes);
		options.add(no);
		return options;
	}

	@Override
	public Object convert(Object currentValue, Object root, Field field) {
		if(currentValue == null || !(currentValue instanceof Boolean)) {
			return null;
		}
		return Boolean.TRUE.equals(currentValue) ? "是" : "否";
	}
}
